package com.sunburst.demo.actor.showcases.account;

import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedAbstractActor;
import akka.event.Logging;
import akka.event.LoggingAdapter;
import akka.japi.Procedure;
import akka.japi.function.Procedure2;
import scala.PartialFunction;
import scala.runtime.BoxedUnit;

import java.time.LocalDateTime;

/**
 * 账户
 */
public class AccountActor extends UntypedAbstractActor {

    private final LoggingAdapter log = Logging.getLogger(getContext().getSystem(), this);

    /**
     * 帐户实体
     */
    private AccountDO accountDO;

    public AccountActor() {
    }

    public AccountActor(AccountDO accountDO) {
        this.accountDO = accountDO;
    }

    public static Props create(AccountDO accountDO) {
        return Props.create(AccountActor.class, accountDO);
    }


    @Override
    public void onReceive(Object message) throws Throwable {
        if (message instanceof AccountCmd) {
            log.info("==== receive cmd: {} ", message);

            AccountCmd cmd = (AccountCmd) message;

            AccountCmdTypeEnum cmdType = cmd.getCmdType();
            String cmdData = cmd.getCmdData();


            Long amount = accountDO.getAmount();

            if (AccountCmdTypeEnum.TRANSFER_IN == cmdType) {
                // 转入金额增加
                amount += Long.parseLong(cmdData);

                // 更新金额
                accountDO.setAmount(amount);
                // 更新时间
                accountDO.setUpdateTime(LocalDateTime.now());

                // 回复帐户内容
                getSender().tell(accountDO.getUpdateTime(), getSelf());
            } else if (AccountCmdTypeEnum.TRANSFER_OUT == cmdType) {
                // 转出金额减少
                amount -= Long.parseLong(cmdData);

                // 更新金额
                accountDO.setAmount(amount);
                // 更新时间
                accountDO.setUpdateTime(LocalDateTime.now());


                // 资金转入借方帐户
                getSender().tell(new AccountCmd(AccountCmdTypeEnum.TRANSFER_IN, "收款", cmdData), getSelf());

                // 回复帐户内容
                getSender().tell(accountDO.getUpdateTime(), getSelf());
            } else if (AccountCmdTypeEnum.QUERY == cmdType) {
                // 回复帐户内容

                getSender().tell(accountDO, getSelf());
            } else {
                log.error("==== receive cmd not handler : {} ", message);
            }

        } else if (message instanceof AccountDO) {
            log.info("==== receive reply entity: {} ", message);
        } else {
            log.error("==== receive msg not handler : {} ", message);
        }

    }

}
